package com.xy6.jvm.thread.synchronizer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

/**
 * DountDownLatch 减数计数器锁示例
 * 
 * @author zhang
 * @since 2018-05-04
 */
public class ConcurrentTimer {
	
	private ConcurrentTimer(){
	}

	/**
	 * simple framework for timing concurrent execution
	 * 
	 * @param executor
	 * @param concurrency
	 * @param action
	 * @return
	 * @throws InterruptedException
	 */
	public static long time(Executor executor, int concurrency, final Runnable action) throws InterruptedException {
		final CountDownLatch ready = new CountDownLatch(concurrency);
		final CountDownLatch start = new CountDownLatch(1);
		final CountDownLatch done = new CountDownLatch(concurrency);
		for (int i = 0; i < concurrency; i++) {
			executor.execute(new Runnable() {
				@Override
				public void run() {
					// tell timer we're ready
					ready.countDown();
					try {
						// wait till peers are ready
						start.await();
						action.run();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						// tell timer we're done
						done.countDown();
					}
				}
			});
		}
		// wait for all workers to be ready
		ready.await();
		long startNanos = System.nanoTime();
		// and they're off
		start.countDown();
		// wait for all workers to finish
		done.await();
		return System.nanoTime() - startNanos;
	}

}
